package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.ConnectTimeoutException;

/**
 * 国航航班分析
 * @author xhyao
 *
 */
public class GetFlightListAC {

/**
 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
 * @param queryInfo
 * @return
 * @throws Exception
 */
	public ResultInfo getResultInfo(QueryInfo queryInfo){
		String responseText = "";
		ResultInfo resultInfo = null;
		//查询条件不合法
		if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
			return null;
		}
 
		HttpRequestProxy proxy = new HttpRequestProxy();
		Map postData   = new HashMap();
		Map header     = new HashMap();
		
		//请求头部
		header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
	    //使用POST请求，赋值post数据
		postData.put("tripType", "oneway");
		postData.put("orgCity", queryInfo.getOrgCity());
		postData.put("dstCity", queryInfo.getDesCity());
		postData.put("takeoffDate", queryInfo.getDateString());
		postData.put("returnDate", queryInfo.getDateString());
		postData.put("cabinClass", "special");
		postData.put("orgID", "CAB2C");
		postData.put("isContractSale", "N");
		postData.put("travelers", "1");
		postData.put("tripType", "oneway");
		postData.put("step", "1");
		postData.put("airkind", "oneway");
		postData.put("adultTravelers", "1");
		postData.put("childTravelers", "0");
		postData.put("lan", "CN");
		postData.put("needCalShop", "onlyselect");
		postData.put("fltShopStep", "0");
		postData.put("isNewFltShopQuery", "true");
 
		try { 
		  responseText = proxy.doRequest(
 	    "http://airchina.travelsky.com/cab2c/FlightSearch_n.do", postData, header,"GBK");
		resultInfo = (ResultInfo)analyzeResopnseText(responseText);
		}
        catch (ConnectTimeoutException e) {   //超时
		// TODO: handle exception
		if (resultInfo==null) {
			resultInfo = new ResultInfo();
		}
		resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
		e.printStackTrace();
	} 
        catch (Exception e) {                //其他异常
		// TODO: handle exception
		if (resultInfo==null) {
			resultInfo = new ResultInfo();
		}
		resultInfo.setStatus(StaticParameter.analyzeStatusError);
		e.printStackTrace();
	}
  	return resultInfo;
	 
}
 
	
	/**
	 * 根据国航网站返回的responseText通过正则表达式分析出结果
	 * @param source  返回的responseText
	 * @return        结果列表 
	 */
	public ResultInfo analyzeResopnseText(String source) throws Exception{
		 
	     PriceInfo priceInfo = null;
	     List priceList  =  null;
	     ResultInfo resultInfo = new ResultInfo();  //结果对象
 		 String[] parts = source.split("<div id=\"priceDIVs1\">"); //将每一个航班区分开来
		   // System.out.println(source);

		     String[] airPort = new String[2];  //出发机场和目的机场
		     ArrayList flightInfos = new ArrayList();  //存放所有的航班信息
		     String regexAirPort ="<span class=\"headcity\">(.*?)</span>";  //

		     String regex = "<div class=\"oneflight\" name=\"aflight\" id=\"aflight\" time=\"(.*?)\" price=\"\" fltrph=\"(.*?)\" lowercabinindex=\"\">\\s*<div class=\"flightinfo\">\\s*<div class=\"flighticon\"></div>\\s*<div class=\"flightnumber\">(.*?)</div>\\s*<div class=\"flightMark\">(.*)</div>\\s*<div class=\"avtimediv\">(.*?)</div>\\s*<div class=\"avtimediv\">(.*?)</div>\\s*<div class=\"flighttype\"><script type=\"text/javascript\">displayPlaneDetail.{1}\"(.*?)\".{1}</script></div>";
		 
 
		     String priceRegex = "onclick=\"changeprice1.{1}'(.*?)','(.*?)','(.*?)',\\s*'(.*?)'\\s*,'(.*?)'.{1}\"/></div>\\s*(.*?)舱</div>";
//		     onclick="changeprice1('011301','公务舱','2260',	
//					
//					'退票收5%手续费'
//				
//				,'10/011301/C/PUB%flightshop/0/0')"/></div>
//				C舱</div>

		 	 Pattern pAirPort = Pattern.compile(regexAirPort,Pattern.CASE_INSENSITIVE);
		     Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
		     Pattern pPrice = Pattern.compile(priceRegex,Pattern.CASE_INSENSITIVE);

		     Matcher maAirPort = pAirPort.matcher(source); 
		     FlightInfo tempInfo = null;
		     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
		     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
		     boolean tempIsFirstForAll = true;
		     //依次取出每个航班的信息,因为parst[0]中没有航班信息，所以数组下标从1开始
			 for(int j=1;j<parts.length;j++){
				 tempInfo = new FlightInfo();
				 priceList  =  new ArrayList();
				 //起飞城市和目的城市
				 tempInfo.setOrgCity(airPort[0]);  
			     tempInfo.setDesCity(airPort[1]);
		 
			     Matcher matcher = p.matcher(parts[j]);
			     Matcher mPrice = pPrice.matcher(parts[j]);
			     if(matcher.find()){
			    	// tempInfo.setFlightFlagForAC(matcher.group(2)); 
			    	 tempInfo.setFlightNo(matcher.group(3).trim());
			         String tempString  = matcher.group(4).trim();  //是否经停
			         
			         if (tempString.indexOf("stop")>=0) {  //经停
						tempInfo.setStopOver(true);
					}
			    	 if (tempString.indexOf("codeshare")>=0) {   //代码共享
						
			    		 
					}
			    	 tempInfo.setTakeOffTime(matcher.group(5).trim());
			    	 tempInfo.setArriveTime(matcher.group(6).trim());
			    	 tempInfo.setPlaneType(matcher.group(7).trim());	 
			     }
		    	 double tempMinPrice = 0.0;
		    	 double tempMaxPrice = 0.0;
		    	 boolean isFirst = true;
			     while(mPrice.find()){
			    	  priceInfo = new PriceInfo();
			          priceInfo.setPrice(Double.parseDouble(mPrice.group(3).trim()));  //价格
			    	  priceInfo.setRemind(mPrice.group(4).trim());  //客户需知
			    	  priceInfo.setSpace(mPrice.group(6).trim());   //舱位
			    	  priceList.add(priceInfo);
			    	  //一个航班不同cabin的最低和最高价格获取
			    	  if (isFirst) {
			    		  tempMinPrice = priceInfo.getPrice();
			    		  tempMaxPrice = priceInfo.getPrice();
			    		  tempInfo.setMinprice(tempMinPrice);
			    		  tempInfo.setMaxprice(tempMaxPrice);
			    		  isFirst = false;
					}
			    	 
			    	  //获取同一个航班的不同舱位中的最高和最低价格
					     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
					    	 tempMinPrice = priceInfo.getPrice();
							}
					     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
					    	 tempMaxPrice = priceInfo.getPrice(); 
						}
					     tempInfo.setMaxprice(tempMaxPrice);
					     tempInfo.setMinprice(tempMinPrice);
			     }
			     tempInfo.setPrice(priceList);
			     flightInfos.add(tempInfo);
			     //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
			     if (tempIsFirstForAll) {      //初始值
			    	 tempMinPriceForAll = tempInfo.getMinprice();
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
			    	 tempIsFirstForAll  = false;
				}
			     if (tempMinPriceForAll>tempInfo.getMinprice()) {   
 
			    	 tempMinPriceForAll = tempInfo.getMinprice();
				}
			     if (tempMaxPriceForAll<tempInfo.getMaxprice()) {
				 
					 tempMinPriceForAll = tempInfo.getMaxprice();
				}
		    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
		    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll);
			     
			 }
			 
			    resultInfo.setResultList(flightInfos);	  
	 		 	 
				return resultInfo;
	}
}
